import { ref, watch } from 'vue'
import { useModal } from '../composables/useModal'
import { API_URL } from '../config/apiConfig'
import { getCookie } from '../utils/cookieUtils'

export function useCustomRuleModal(props: { show: boolean }, emit: any) {
  const { modalContentStyle, openModal, closeModal, handleModalClick } = useModal()
  
  const ruleFile = ref<File | null>(null)
  const showTemplatePreview = ref(false)


  watch(() => props.show, (newShow) => {
    if (newShow) {
      openModal()
    } else {
      showTemplatePreview.value = false
    }
  })

  const closeModalHandler = () => {
    closeModal(emit)
  }

  const handleModalClickHandler = (e: Event) => {
    handleModalClick(e, emit)
  }

  const generateTemplate = async () => {
    if (!ruleFile.value) {
      alert('请上传Word文档')
      return
    }
    
    try {
      const formData = new FormData()
      formData.append('file', ruleFile.value)
      
      // 从cookie获取认证token
      const token = getCookie('token')
      
      if (!token) {
        alert('您尚未登录或登录已过期，请重新登录')
        return
      }

      const response = await fetch(`${API_URL}/demo/convert`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: formData,
        credentials: 'include' // 确保包含凭证（cookies）
      })

      if (!response.ok) {
        // 尝试解析错误消息，如果失败则使用状态码
        try {
          const errorData = await response.json()
          throw new Error(errorData.message || `请求失败: ${response.status}`)
        } catch {
          throw new Error(`请求失败: ${response.status}`)
        }
      }

      // 请求成功，显示模板预览
      showTemplatePreview.value = true
      setTimeout(() => {
        const previewElement = document.querySelector('.template-preview')
        previewElement?.scrollIntoView({ behavior: 'smooth' })
      }, 100)
    } catch (error) {
      console.error('生成模板失败:', error)
      alert(`生成模板失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  const downloadTemplate = () => {
    emit('showExcel')
  }

  return {
    modalContentStyle,
    ruleFile,
    showTemplatePreview,
    closeModal: closeModalHandler,
    handleModalClick: handleModalClickHandler,
    generateTemplate,
    downloadTemplate
  }
}